from flask import request, jsonify, Blueprint
from flask_login import login_user, logout_user, login_required, current_user

from slewing.extension import db
from slewing.models import User, Dev

user_bp = Blueprint('user', __name__)


@user_bp.route('/register', methods=['POST'])
def user_register():
    """用户注册"""
    json = request.json
    user = User(
        username=json.get("username")
    )
    if User.query.filter_by(username=user.username).first():
        return jsonify(message="Duplicate username"), 205
    user.set_password(json.get('password'))
    db.session.add(user)
    db.session.commit()
    return "Register Succeeded"


@user_bp.route('/login', methods=['Get', 'POST'])
def user_login():
    """用户登录"""
    if request.method == 'POST':
        json = request.json
        username = json.get("username")
        password = json.get("password")
        remember = json.get("remember")

        user = User.query.filter_by(username=username).first()
        if user:
            # 验证用户名和密码
            if user.validate_password(password):
                login_user(user, remember)  # 登入用户
                return jsonify(message="{} login successful".format(current_user.username))
            return jsonify(message="wrong username or password"), 206
        else:
            return jsonify(message="User does not exist, please register"), 207
    # cookie登录
    else:
        if current_user.is_authenticated:
            return jsonify(message="{} login successful by cookie".format(current_user.username))
        else:
            return jsonify(message="cookie error"), 208


@user_bp.route('/logout')
@login_required  # 视图保护
def user_logout():
    """用户注销"""
    name = current_user.username
    logout_user()
    return jsonify(message="{} logout succeeded".format(name))


@user_bp.route('/myDevices', methods=['GET'])
@login_required
def get_devices():
    size = len(current_user.dev)
    devices = {}
    data = {"total": size, "dev": devices}
    for i in range(size):
        devices["dev" + str(i + 1)] = current_user.dev[i].mac

    print(devices)
    return data


@user_bp.route('/delete_dev/<string:macID>', methods=['GET'])
@login_required
def delete_dev(macID):
    """用户删除蓝牙节点"""
    dev = Dev.query.filter_by(mac=macID.upper()).first()
    if dev:
        current_user.dev.remove(dev)
        db.session.commit()
        return jsonify(message="pop the device successfully")
    else:
        return jsonify(message="mac id error"), 400


@user_bp.route('/add_dev/<string:macID>', methods=['GET'])
@login_required
def add_dev(macID):
    """用户添加蓝牙节点"""
    dev = Dev.query.filter_by(mac=macID.upper()).first()
    if dev:
        current_user.dev.append(dev)
        db.session.commit()
        return jsonify(message="bind the device successfully")
    else:
        return jsonify(message="mac id error"), 400
